import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbfdgroup } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/groups/edit.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = ITbfdgroup;

/**
 * 组别编辑服务
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { groupid, ...body } = req.body as Message;
		if (!body
			|| !groupid
			|| !body.name
		) {
			res.status(200).json({
				ok: false,
				message: '缺少必要的参数'
			});
			return;
		}
		// 检查修改后的记录是否存在
		const r = await tbfdgroup().first('*')
			.where({
				name: body.name
			}).andWhereNot({
				groupid
			});
		if (r) {
			res.status(200).json({ ok: false, message: '数据已存在' });
			return;
		}
		await tbfdgroup().update(body).where({
			groupid
		});

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
